package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.model.Permission;
import com.property.demo.repository.PermissionRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/permissions")
public class PermissionController {
    
    private static final Logger logger = LoggerFactory.getLogger(PermissionController.class);
    
    @Autowired
    private PermissionRepository permissionRepository;
    
    @GetMapping
    public ResponseEntity<?> getAllPermissions() {
        logger.info("获取所有权限");
        
        try {
            List<Permission> permissions = buildPermissionTree();
            logger.info("成功获取所有权限 - 数量: {}", permissions.size());
            return ResponseEntity.ok(permissions);
        } catch (Exception e) {
            logger.error("获取所有权限失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse(false, "获取所有权限失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getPermissionById(@PathVariable Long id) {
        logger.info("获取权限详情 - ID: {}", id);
        
        try {
            Optional<Permission> permissionOpt = permissionRepository.findById(id);
            
            if (!permissionOpt.isPresent()) {
                logger.warn("未找到权限 - ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            Permission permission = permissionOpt.get();
            logger.info("成功获取权限详情 - ID: {}, 名称: {}", id, permission.getName());
            return ResponseEntity.ok(permission);
        } catch (Exception e) {
            logger.error("获取权限详情失败 - ID: {}, 错误: {}", id, e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse(false, "获取权限详情失败: " + e.getMessage()));
        }
    }
    
    @PostMapping
    public ResponseEntity<?> createPermission(@RequestBody Permission permission) {
        logger.info("创建权限 - 名称: {}, 编码: {}", permission.getName(), permission.getCode());
        
        try {
            if (permissionRepository.existsByCode(permission.getCode())) {
                logger.warn("创建权限失败 - 权限编码已存在: {}", permission.getCode());
                return ResponseEntity.badRequest().body(new ApiResponse(false, "权限编码已被使用!"));
            }

            Permission savedPermission = permissionRepository.save(permission);
            
            logger.info("权限创建成功 - ID: {}, 名称: {}", savedPermission.getId(), savedPermission.getName());
            return ResponseEntity.ok(savedPermission);
        } catch (Exception e) {
            logger.error("创建权限失败 - 名称: {}, 错误: {}", permission.getName(), e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse(false, "创建权限失败: " + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<?> updatePermission(@PathVariable Long id, @RequestBody Permission permissionDetails) {
        logger.info("更新权限 - ID: {}", id);
        
        try {
            Optional<Permission> permissionOpt = permissionRepository.findById(id);
            
            if (!permissionOpt.isPresent()) {
                logger.warn("更新权限失败 - 未找到权限 ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            Permission permission = permissionOpt.get();
            
            // 检查权限编码是否已被其他权限使用
            if (!permission.getCode().equals(permissionDetails.getCode()) && 
                permissionRepository.existsByCode(permissionDetails.getCode())) {
                logger.warn("更新权限失败 - 权限编码已被使用: {}", permissionDetails.getCode());
                return ResponseEntity.badRequest().body(new ApiResponse(false, "权限编码已被使用!"));
            }
            
            // 更新权限信息
            permission.setName(permissionDetails.getName());
            permission.setCode(permissionDetails.getCode());
            permission.setType(permissionDetails.getType());
            permission.setPath(permissionDetails.getPath());
            permission.setParentId(permissionDetails.getParentId());
            permission.setSort(permissionDetails.getSort());
            permission.setDescription(permissionDetails.getDescription());
            
            Permission updatedPermission = permissionRepository.save(permission);
            
            logger.info("权限更新成功 - ID: {}, 名称: {}", updatedPermission.getId(), updatedPermission.getName());
            return ResponseEntity.ok(updatedPermission);
        } catch (Exception e) {
            logger.error("更新权限失败 - ID: {}, 错误: {}", id, e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse(false, "更新权限失败: " + e.getMessage()));
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deletePermission(@PathVariable Long id) {
        logger.info("删除权限 - ID: {}", id);
        
        try {
            Optional<Permission> permissionOpt = permissionRepository.findById(id);
            
            if (!permissionOpt.isPresent()) {
                logger.warn("删除权限失败 - 未找到权限 ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            // 检查是否有子权限
            List<Permission> children = permissionRepository.findByParentIdOrderBySort(id);
            if (!children.isEmpty()) {
                logger.warn("删除权限失败 - 存在子权限, 数量: {}", children.size());
                return ResponseEntity.badRequest().body(new ApiResponse(false, "该权限包含子权限，无法删除!"));
            }
            
            permissionRepository.deleteById(id);
            
            logger.info("权限删除成功 - ID: {}", id);
            return ResponseEntity.ok(new ApiResponse(true, "权限删除成功!"));
        } catch (Exception e) {
            logger.error("删除权限失败 - ID: {}, 错误: {}", id, e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse(false, "删除权限失败: " + e.getMessage()));
        }
    }
    
    // 构建权限树形结构
    private List<Permission> buildPermissionTree() {
        List<Permission> result = new ArrayList<>();
        
        // 获取所有顶级权限
        List<Permission> rootPermissions = permissionRepository.findByParentIdIsNullOrderBySort();
        
        // 递归构建树形结构
        for (Permission rootPermission : rootPermissions) {
            buildPermissionTreeRecursive(rootPermission);
            result.add(rootPermission);
        }
        
        return result;
    }
    
    // 递归构建权限树
    private void buildPermissionTreeRecursive(Permission parent) {
        List<Permission> children = permissionRepository.findByParentIdOrderBySort(parent.getId());
        
        if (!children.isEmpty()) {
            parent.setChildren(children);
            
            for (Permission child : children) {
                buildPermissionTreeRecursive(child);
            }
        }
    }
} 